import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
import QtQuick.Window 2.15
import QtGraphicalEffects 1.15

// 使用 ApplicationWindow 作为根，确保创建可见窗口
ApplicationWindow {
    id: root
    // 自适应缩放：以 800 的短边为基准
    property real uiScale: Math.min(width, height) / 800
    property int screenWidth: Qt.application.screens.length > 0 ? Qt.application.screens[0].width : 720
    property int screenHeight: Qt.application.screens.length > 0 ? Qt.application.screens[0].height : 1280
    width: screenWidth
    height: screenHeight
    visible: true

    // 背景渐变
    Rectangle {
        anchors.fill: parent
        gradient: Gradient {
            GradientStop { position: 0.0; color: "#4facfe" }
            GradientStop { position: 1.0; color: "#00f2fe" }
        }
    }

    // 主内容区域
    ScrollView {
        anchors.fill: parent
        contentWidth: width
        clip: true

        ColumnLayout {
            width: parent.width
            anchors.margins: 20
            spacing: 20

            // 城市信息
            RowLayout {
                Layout.alignment: Qt.AlignHCenter
                Layout.topMargin: 20 * root.uiScale
                spacing: 10 * root.uiScale

                Text {
                    text: weatherFetcher.cityName || "北京"
                    font.pixelSize: 36 * root.uiScale
                    font.bold: true
                    color: "white"
                }

                Button {
                    text: "🔍"
                    background: Rectangle {
                        radius: 20 * root.uiScale
                        color: "#4DFFFFFF"
                    }
                    onClicked: {
                        searchDialog.open();
                    }
                }


            }

            // 当前日期
            Text {
                text: {
                    var date = new Date();
                    var weekdays = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
                    return date.getFullYear() + "年" + 
                           (date.getMonth() + 1) + "月" + 
                           date.getDate() + "日 " + 
                           weekdays[date.getDay()];
                }
                font.pixelSize: 18 * root.uiScale
                color: "white"
                Layout.alignment: Qt.AlignHCenter
            }

            // 加载指示器
            BusyIndicator {
                Layout.alignment: Qt.AlignHCenter
                visible: weatherFetcher.loading
                running: weatherFetcher.loading
            }

            // 天气图标和温度
            RowLayout {
                Layout.alignment: Qt.AlignHCenter
                spacing: 10 * root.uiScale
                visible: !weatherFetcher.loading

                Item {
                    width: 130 * root.uiScale
                    height: 130 * root.uiScale
                    Image {
                        id: iconImage
                        anchors.centerIn: parent
                        width: 120 * root.uiScale
                        height: 120 * root.uiScale
                        fillMode: Image.PreserveAspectFit
                        visible: (weatherFetcher.icon && weatherFetcher.icon.length > 0) && status === Image.Ready
                        source: weatherFetcher.icon
                        asynchronous: true
                        cache: true
                    }
                    // fallback emoji
                    Text {
                        anchors.centerIn: parent
                        visible: !(weatherFetcher.icon && weatherFetcher.icon.length > 0) || iconImage.status === Image.Error
                        text: {
                            var condition = weatherFetcher.weatherCondition;
                            if (condition.includes("晴") || condition.includes("Clear")) return "☀️";
                            if (condition.includes("云") || condition.includes("Cloud")) return "☁️";
                            if (condition.includes("雨") || condition.includes("Rain")) return "🌧️";
                            if (condition.includes("雪") || condition.includes("Snow")) return "❄️";
                            if (condition.includes("雾") || condition.includes("Fog")) return "🌫️";
                            return "🌤️";
                        }
                        font.pixelSize: 120 * root.uiScale
                    }
                }

                Text {
                    text: weatherFetcher.temperature || "--°C"
                    font.pixelSize: 72 * root.uiScale
                    font.bold: true
                    color: "white"
                }
            }

            // 天气状况
            Text {
                text: weatherFetcher.weatherCondition || "--"
                font.pixelSize: 24 * root.uiScale
                color: "white"
                Layout.alignment: Qt.AlignHCenter
                visible: !weatherFetcher.loading
            }

            // 天气详情指标（网格卡片，目标 3 列，自适应降级）
            ColumnLayout {
                Layout.margins: 20 * root.uiScale
                spacing: 12 * root.uiScale
                visible: !weatherFetcher.loading

                Text {
                    text: "当前详情"
                    font.pixelSize: 18 * root.uiScale
                    font.bold: true
                    color: "white"
                    Layout.leftMargin: 4 * root.uiScale
                }

                GridLayout {
                    id: gridCards
                    Layout.fillWidth: true
                    columnSpacing: 12 * root.uiScale
                    rowSpacing: 12 * root.uiScale
                    // 目标 3 列，按宽度自适应降级
                    readonly property int targetCols: 3
                    readonly property real cardMinWidth: 160 * root.uiScale
                    readonly property int computedCols: Math.max(1, Math.min(targetCols, Math.floor(width / (cardMinWidth + columnSpacing))))
                    columns: computedCols

                    Repeater {
                        model: [
                            { label: "体感", value: weatherFetcher.feelsLike || "--" },
                            { label: "湿度", value: weatherFetcher.humidity || "--" },
                            { label: "风向", value: weatherFetcher.windDirection || "--" },
                            { label: "风速", value: weatherFetcher.windSpeed || "--" },
                            { label: "风力", value: weatherFetcher.windScale || "--" },
                            { label: "气压", value: weatherFetcher.pressure || "--" },
                            { label: "能见度", value: weatherFetcher.visibility || "--" },
                            { label: "降水", value: weatherFetcher.precipitation || "--" },
                            { label: "更新时间", value: weatherFetcher.updateTime || "--" }
                        ]
                        delegate: Item {
                            Layout.fillWidth: true
                            Layout.preferredWidth: Math.max(gridCards.cardMinWidth, (gridCards.width - (gridCards.computedCols - 1) * gridCards.columnSpacing) / gridCards.computedCols)
                            Layout.preferredHeight: 100 * root.uiScale

                            DropShadow {
                                anchors.fill: card
                                source: card
                                radius: 12
                                samples: 17
                                color: "#33000000"
                                horizontalOffset: 0
                                verticalOffset: 3
                            }
                            Rectangle {
                                id: card
                                anchors.fill: parent
                                radius: 16 * root.uiScale
                                color: "#55FFFFFF"
                                border.width: 1
                                border.color: "#66FFFFFF"
                                Column {
                                    anchors.fill: parent
                                    anchors.margins: 10 * root.uiScale
                                    spacing: 8 * root.uiScale
                                    Text {
                                        text: modelData.label
                                        color: "#E6FFFFFF"
                                        font.pixelSize: 18 * root.uiScale
                                        horizontalAlignment: Text.AlignHCenter
                                        width: parent.width
                                    }
                                    Text {
                                        text: modelData.value
                                        color: "white"
                                        font.pixelSize: 24 * root.uiScale
                                        font.bold: true
                                        horizontalAlignment: Text.AlignHCenter
                                        width: parent.width
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    // 搜索对话框
    Dialog {
        id: searchDialog
        title: "搜索城市"
        width: Math.min(400, parent.width * 0.9)
        height: 200
        modal: true
        anchors.centerIn: parent

        ColumnLayout {
            anchors.fill: parent
            spacing: 10

            TextField {
                id: cityInput
                placeholderText: "请输入城市名称"
                Layout.fillWidth: true
                onAccepted: {
                    if (text.trim() !== "") {
                        weatherFetcher.fetchWeather(text.trim());
                        searchDialog.close();
                    }
                }
            }

            RowLayout {
                Layout.alignment: Qt.AlignRight
                spacing: 10

                Button {
                    text: "取消"
                    onClicked: searchDialog.close()
                }

                Button {
                    text: "查询"
                    onClicked: {
                        if (cityInput.text.trim() !== "") {
                            weatherFetcher.fetchWeather(cityInput.text.trim());
                            searchDialog.close();
                        }
                    }
                }
            }
        }
    }

    // 城市列表模型
    ListModel {
        id: cityListModel
        // 预定义一些示例城市
        Component.onCompleted: {
            append({modelData: "北京"});
            append({modelData: "上海"});
            append({modelData: "广州"});
            append({modelData: "深圳"});
        }
    }

    // 应用启动时加载默认城市
    Component.onCompleted: {
        // 设置接口盒子凭证（请替换为你自己的 id 与 key）
        if (typeof weatherFetcher.setApiHzId === "function") {
            weatherFetcher.setApiHzId("10009741")
        }
        if (typeof weatherFetcher.setApiHzKey === "function") {
            weatherFetcher.setApiHzKey("2dd7ba8d86a785f3a867f71c2a3fc5bc")
        }
        weatherFetcher.fetchWeather("北京");
    }

    // 监听天气数据获取结果
    Connections {
        target: weatherFetcher
        function onWeatherFetched(success, error) {
            if (!success && error) {
                console.log("获取天气数据失败:", error);
            }
        }
    }
}
